package com.endbd.systemmanagement.service.job;

import com.endbd.feignapi.model.system.Job;
import com.endbd.systemmanagement.dao.job.JobDao;
import com.endbd.systemmanagement.model.JobCondition;
import com.endbd.systemmanagement.model.ModuleImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class JobServiceImpl implements JobService{

  @Autowired
  private JobDao jobDao;

  @Override
  public List<Job> getJobList() {
    JobCondition jobCondition = new JobCondition();
    return jobDao.getJobList(jobCondition);
  }

  @Override
  public List<Job> queryCondition(JobCondition jobCondition) {
    return jobDao.getJobList(jobCondition);
  }

  @Override
  public boolean createJob(Job job) {
    job.setJobState("1");
    return jobDao.createJob(job)==1;
  }

  @Override
  public int zx(Integer id, String state) {
    if("1".equals(state)) state="0";
    else state="1";
    return jobDao.zx(id,state);
  }

  @Override
  public boolean updateJob(Job job) {
    return jobDao.updateJob(job)==1;
  }

  @Override
  public List<ModuleImpl> getModules() {
    return jobDao.getModules();
  }

  @Override
  public List<Integer> getGrant(Integer id) {
    return jobDao.getGrant(id);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean endowGrant(Integer id, List<Integer> initKey, List<Integer> checked) throws Exception{
    List<Integer> list=new ArrayList<>();
    for (Integer integer : initKey) {
      if(!checked.contains(integer)){
        list.add(integer);
      }
    }
    int num;
    if(!list.isEmpty()){
      num=jobDao.depriveGrant(id,list);
      if(num == list.size()){
        list.clear();
      }else{
        throw new Exception();
      }
    }
    for (Integer integer : checked) {
      if(integer>5 && !initKey.contains(integer)){
        list.add(integer);
      }
    }
    int number;
    if(!list.isEmpty()) {
      number=jobDao.endowGrant(id,list);
      if(number==list.size()){
        return true;
      }else{
        throw new Exception();
      }
    }
    return true;
  }
}
